// src/pages/PosterPage.js

export default class PosterPage {
  constructor(canvas, ctx, pageManager, resourceManager, screenAdapter, api, userManager) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.pageManager = pageManager; // 用于返回上一页
    this.screenAdapter = screenAdapter; // 用于屏幕适配
    this.api = api;
    this.userManager = userManager;

    this.posterImage = null;
    this.posterPath = '';
  }

  /**
   * 页面初始化，接收海报路径
   * @param {string} posterPath - 海报的临时文件路径
   */
  async initialize(posterPath) {
    this.posterPath = posterPath;
    console.log('[PosterPage] 初始化，海报路径:', this.posterPath);

    // 加载海报图片
    await this._loadPosterImage();
  }

  async _loadPosterImage() {
    return new Promise((resolve, reject) => {
      const img = wx.createImage();
      img.onload = () => {
        console.log('[PosterPage] 海报图片加载成功');
        this.posterImage = img;
        resolve();
      };
      img.onerror = (err) => {
        console.error('[PosterPage] 海报图片加载失败:', err);
        reject(err);
      };
      img.src = this.posterPath;
    });
  }

  onEnter() {
    // 页面进入时的逻辑，如果需要的话
    console.log('[PosterPage] 进入海报页面');
  }

  onExit() {
    // 页面退出时的逻辑，清理资源
    console.log('[PosterPage] 退出海报页面');
    this.posterImage = null;
    this.posterPath = '';
  }

  update(dt) {
    // 海报页面是静态的，一般不需要更新逻辑
  }

  render() {
    if (!this.posterImage) return;

    const ctx = this.ctx;
    const canvas = this.canvas;

    // 1. 绘制半透明黑色背景
    // ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
    // ctx.fillRect(0, 0, canvas.width, canvas.height);

    // --- 旋转绘制逻辑 ---
    ctx.save(); // 保存当前画布状态

    ctx.setTransform(1, 0, 0, 1, 0, 0);

    // --- 简单的缩放和居中绘制 ---
    const imgW = this.posterImage.width;
    const imgH = this.posterImage.height;
    const canvasW = canvas.width;
    const canvasH = canvas.height;

    // 计算缩放比例，让图片完整显示在屏幕内
    const scale = Math.min(canvas.width / imgW, canvas.height / imgH);

    const drawW = imgW * scale;
    const drawH = imgH * scale;
    const drawX = (canvasW - drawW) / 2;
    const drawY = (canvasH - drawH) / 2;

    // 直接绘制
    ctx.drawImage(this.posterImage, drawX, drawY, drawW, drawH);

    ctx.restore(); // 恢复画布状态，避免影响后续绘制
  }

  /**
   * 处理触摸结束事件
   */
  handleTouchEnd(event) {
    // 在海报页面，任何点击都返回上一页
    console.log('[PosterPage] 用户点击，返回上一页');
    // 假设是从 home 页过来的，返回 home 页
    // 你可以根据实际情况修改返回的页面
    this.pageManager.showPage('profile');
  }

  // 其他触摸事件可以留空或实现其他逻辑
  handleTouchStart(event) { }
  handleTouchMove(event) { }
  handleTouchCancel(event) { }
}
